#include "BaseSceneView.h"

BaseSceneView::BaseSceneView(QWidget* parent)
	: QWidget(parent)
{
	this->setAcceptDrops(true);//允许往窗口拖放
	this->setFixedSize(QSize(320, 480));
	view = new QGraphicsView(this);//实例化View
	view->setMouseTracking(true);
	view->setFixedSize(this->size());
	view->setAcceptDrops(false);
	view->setScene(&scene);//给View设置场景
	mThread = new HandlerThread(this, this);//子线程，用于处理耗时任务，处理完成后发送信号
	//接收上面线程执行完成后发出的信号
	connect(mThread, &HandlerThread::updateUI, this, [=](QPixmap pixmap) {
		updateImage(pixmap);
		});
}
void BaseSceneView::dragEnterEvent(QDragEnterEvent* event) {
	QStringList acceptedFileTypes;
	acceptedFileTypes.append("jpeg");
	acceptedFileTypes.append("png");
	acceptedFileTypes.append("bmp");
	acceptedFileTypes.append("jpg");//设置可以接受的文件格式类型
	if (event->mimeData()->hasUrls() && event->mimeData()->urls().count() == 1) {
		QFileInfo file(event->mimeData()->urls().at(0).toLocalFile());
		if (acceptedFileTypes.contains(file.suffix().toLower())) {
			event->acceptProposedAction();
		}
	}
	else {
		QMessageBox::critical(this, "Error", "count not load mulit files");
	}
}

//拖动内容到窗口
void BaseSceneView::dropEvent(QDropEvent* event) {
	scene.clear();
	QFileInfo file(event->mimeData()->urls().at(0).toLocalFile());
}

void BaseSceneView::resizeEvent(QResizeEvent* event) {

}

void BaseSceneView::onHSliderValueChanged(int value) {


}
void BaseSceneView::addPixmap(QPixmap pixmap) {
	scene.clear();
	QGraphicsPixmapItem* item = new QGraphicsPixmapItem(pixmap.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
	scene.addItem(item);//给场景添加内容
}

void BaseSceneView::addImage(QImage image) {
	scene.clear();
	QPixmap pixmap = QPixmap::fromImage(image);
	QGraphicsPixmapItem* item = new QGraphicsPixmapItem(pixmap.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
	scene.addItem(item);//给场景添加内容
}

void BaseSceneView::addMat(cv::Mat mat) {
	scene.clear();
	QImage image = ImageUtils::matToQImage(mat);
	QPixmap pixmap = QPixmap::fromImage(image);
	QGraphicsPixmapItem* item = new QGraphicsPixmapItem(pixmap.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
	scene.addItem(item);//给场景添加内容
}

void BaseSceneView::updateImage(QPixmap pixmap) {
	addPixmap(pixmap);
}


//执行耗时任务（执行耗时任务前需要调用）
void BaseSceneView::execute() {
	mThread->start();
}
QPixmap BaseSceneView::handle() {
	return NULL;
}
void BaseSceneView::setGraphicsViewSize(int width, int height) {
	view->setFixedSize(width, height);
}
BaseSceneView::~BaseSceneView()
{
}
